import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table, Button, Space, Modal, Form, Input, Select, message, Popconfirm, Upload, Avatar } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, UploadOutlined, UserOutlined } from '@ant-design/icons';
import { request } from 'umi';
import moment from 'moment';
import { getAllFranchises } from '@/services/franchise';
import SearchForm from './SearchForm';
import AuthorizedButton from '@/components/Authorized/AuthorizedButton';

// 获取用户列表
const fetchUsers = async (params) => {
  return request('/api/v1/user', {
    method: 'GET',
    params,
  });
};

// 创建用户
const createUser = async (data) => {
  return request('/api/v1/user', {
    method: 'POST',
    data,
  });
};

// 更新用户
const updateUser = async (data) => {
  const { id, ...rest } = data;
  return request(`/api/v1/user/${id}`, {
    method: 'PUT',
    data: rest,
  });
};

// 删除用户
const deleteUser = async (id) => {
  return request(`/api/v1/user/${id}`, {
    method: 'DELETE',
  });
};

// 获取角色列表
const fetchRoles = async () => {
  return request('/api/v1/role', {
    method: 'GET',
  });
};

const UserList = () => {
  const [users, setUsers] = useState([]);
  const [roles, setRoles] = useState([]);
  const [franchises, setFranchises] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [modalTitle, setModalTitle] = useState('添加用户');
  const [form] = Form.useForm();
  const [editingId, setEditingId] = useState(null);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
  });
  
  // 搜索参数
  const [searchParams, setSearchParams] = useState({});

  // 获取用户列表
  const fetchUserList = async () => {
    try {
      setLoading(true);
      const res = await fetchUsers({
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...searchParams, // 添加搜索参数
      });
      if (res.success) {
        setUsers(res.data.list || []);
        setPagination({
          ...pagination,
          total: res.data.total,
        });
      } else {
        message.error(res.message || '获取用户列表失败');
      }
    } catch (error) {
      console.error('获取用户列表出错:', error);
      message.error('获取用户列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取角色列表
  const fetchRoleList = async () => {
    try {
      const res = await fetchRoles();
      if (res.success) {
        setRoles(res.data.list || []);
      } else {
        message.error(res.message || '获取角色列表失败');
      }
    } catch (error) {
      console.error('获取角色列表出错:', error);
      message.error('获取角色列表失败');
    }
  };

  // 获取加盟商列表
  const fetchFranchiseList = async () => {
    try {
      const res = await getAllFranchises();
      if (res.success) {
        setFranchises(res.data.list || []);
      } else {
        message.error(res.message || '获取加盟商列表失败');
      }
    } catch (error) {
      console.error('获取加盟商列表出错:', error);
      message.error('获取加盟商列表失败');
    }
  };

  useEffect(() => {
    fetchUserList();
    fetchRoleList();
    fetchFranchiseList();
  }, [pagination.current, pagination.pageSize, searchParams]); // 添加searchParams依赖

  // 处理搜索
  const handleSearch = (values) => {
    setSearchParams(values);
    setPagination({
      ...pagination,
      current: 1, // 搜索时重置为第一页
    });
  };

  // 处理重置搜索
  const handleResetSearch = () => {
    setSearchParams({});
    setPagination({
      ...pagination,
      current: 1, // 重置搜索时重置为第一页
    });
  };

  // 表格列定义
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '姓名',
      dataIndex: 'real_name',
      key: 'real_name',
    },
    {
      title: '头像',
      dataIndex: 'avatar',
      key: 'avatar',
      render: (avatar) => (
        <Avatar 
          src={avatar} 
          icon={<UserOutlined />} 
          size="small"
        />
      ),
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      key: 'mobile',
      render: (text) => text || '-',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      render: (text) => text || '-',
    },
    {
      title: '加盟商',
      dataIndex: 'franchise_id',
      key: 'franchise_id',
      render: (franchiseId) => {
        const franchise = franchises.find(f => f.id === franchiseId);
        return franchise ? franchise.name : (franchiseId === 0 ? '总部' : '-');
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <span style={{ color: status === 1 ? '#52c41a' : '#ff4d4f' }}>
          {status === 1 ? '正常' : '禁用'}
        </span>
      ),
    },
    {
      title: '角色',
      dataIndex: 'role_id',
      key: 'role_id',
      render: (roleId) => {
        const role = roles.find(r => r.id === roleId);
        return role ? role.name : '-';
      },
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
      render: (text) => moment(text*1000).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <AuthorizedButton 
            permission="user:update"
            type="primary" 
            icon={<EditOutlined />} 
            size="small"
            onClick={() => handleEdit(record)}
          >
            编辑
          </AuthorizedButton>
          <Popconfirm
            title="确定要删除此用户吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <AuthorizedButton 
              permission="user:delete"
              type="primary" 
              danger 
              icon={<DeleteOutlined />} 
              size="small"
            >
              删除
            </AuthorizedButton>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 处理添加用户
  const handleAdd = () => {
    setModalTitle('添加用户');
    setEditingId(null);
    form.resetFields();
    form.setFieldsValue({ status: 1 }); // 默认状态为正常
    setModalVisible(true);
  };

  // 处理编辑用户
  const handleEdit = (record) => {
    setModalTitle('编辑用户');
    setEditingId(record.id);
    form.setFieldsValue({
      username: record.username,
      real_name: record.real_name,
      avatar: record.avatar,
      mobile: record.mobile,
      email: record.email,
      status: record.status,
      roleId: record.role_id,
      franchiseId: record.franchise_id,
    });
    setModalVisible(true);
  };

  // 处理删除用户
  const handleDelete = async (id) => {
    try {
      const res = await deleteUser(id);
      if (res.success) {
        message.success('删除成功');
        fetchUserList();
      } else {
        message.error(res.message || '删除失败');
      }
    } catch (error) {
      console.error('删除用户出错:', error);
      message.error('删除失败');
    }
  };

  // 处理表单提交
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      if (editingId) {
        // 更新用户
        const res = await updateUser({
          id: editingId,
          ...values,
          role_id: values.roleId,
          franchise_id: values.franchiseId
        });
        if (res.success) {
          message.success('更新成功');
          setModalVisible(false);
          fetchUserList();
        } else {
          message.error(res.message || '更新失败');
        }
      } else {
        // 创建用户
        const res = await createUser({
          ...values,
          role_id: values.roleId,
          franchise_id: values.franchiseId
        });
        if (res.success) {
          message.success('创建成功');
          setModalVisible(false);
          fetchUserList();
        } else {
          message.error(res.message || '创建失败');
        }
      }
    } catch (error) {
      console.error('提交表单出错:', error);
    }
  };

  // 处理表格分页变化
  const handleTableChange = (pagination) => {
    setPagination({
      ...pagination,
    });
  };

  return (
    <PageContainer>
      <Card
        title="用户管理"
        extra={
          <AuthorizedButton 
            permission="user:create"
            type="primary" 
            icon={<PlusOutlined />}
            onClick={handleAdd}
          >
            添加用户
          </AuthorizedButton>
        }
      >
        <SearchForm onSearch={handleSearch} onReset={handleResetSearch} />
        <Table
          columns={columns}
          dataSource={users}
          rowKey="id"
          loading={loading}
          pagination={pagination}
          onChange={handleTableChange}
          scroll={{ x: 1100 }}
        />
      </Card>

      <Modal
        title={modalTitle}
        visible={modalVisible}
        onOk={handleSubmit}
        onCancel={() => setModalVisible(false)}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input placeholder="请输入用户名" disabled={!!editingId} />
          </Form.Item>
          {!editingId && (
            <Form.Item
              name="password"
              label="密码"
              rules={[{ required: true, message: '请输入密码' }]}
            >
              <Input.Password placeholder="请输入密码" />
            </Form.Item>
          )}
          <Form.Item
            name="real_name"
            label="姓名"
            rules={[{ required: true, message: '请输入姓名' }]}
          >
            <Input placeholder="请输入姓名" />
          </Form.Item>
          <Form.Item
            name="avatar"
            label="头像"
          >
            <Input placeholder="请输入头像URL" />
          </Form.Item>
          <Form.Item
            name="mobile"
            label="手机号"
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>
          <Form.Item
            name="email"
            label="邮箱"
          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>
          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select placeholder="请选择状态">
              <Select.Option value={1}>正常</Select.Option>
              <Select.Option value={0}>禁用</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="franchiseId"
            label="加盟商"
            rules={[{ required: true, message: '请选择加盟商' }]}
            initialValue={0}
          >
            <Select placeholder="请选择加盟商">
              <Select.Option key={0} value={0}>总部</Select.Option>
              {franchises.map(franchise => (
                <Select.Option key={franchise.id} value={franchise.id}>
                  {franchise.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="roleId"
            label="角色"
            rules={[{ required: true, message: '请选择角色' }]}
          >
            <Select placeholder="请选择角色">
              {roles.map(role => (
                <Select.Option key={role.id} value={role.id}>
                  {role.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default UserList;